<template>
  <div class="role-container">
    <maskLayer :isLoading="isLoading"/>
    <div class="top-container">
      <a-button type="primary" size="large" @click="addRoleClick">新增角色</a-button>
    </div>
    <div class="bot-container" v-if="allRoleDataList && allRoleDataList.length">
      <a-table class="table-container" :data-source="allRoleDataList" :scroll="{ y: 73+`vh` }"
               :pagination="{ pageSize: 15, showSizeChanger:false }">
        <a-table-column title="名称" data-index="roleName" :ellipsis="true" align="center"/>
        <a-table-column title="用户绑定数" data-index="boundUserCount" :ellipsis="true" align="center"/>
        <a-table-column title="可操作菜单" data-index="action" :ellipsis="true" align="center">
          <template #default="{ record }">
            <a-button type="primary" size="large" @click="viewDetailsClick(record)">查看</a-button>
          </template>
        </a-table-column>
        <a-table-column title="操作" data-index="action" :ellipsis="true" align="center">
          <template #default="{ record }">
            <a-button type="primary" size="large" @click="editRoleClick(record)">更新</a-button>
            <a-button type="primary" size="large" style="margin-left: 10px" danger @click="deleteRoleClick(record)">
              删除
            </a-button>
          </template>
        </a-table-column>
      </a-table>
      <container title="可操作菜单" style="width: 40%;height: 100%;" flex-direction="">
        <template #action>
          <a-popconfirm title="您登录的账号正在使用当前角色，确定修改吗？" ok-text="确定"
                        cancel-text="放弃" :open="popConfirmIsOpen" @confirm="updateRoleMenu(true)"
                        @cancel="popConfirmIsOpen = false">
            <a-button type="primary" v-if="nowSelectRole" @click="updateRoleMenuClick">
              更新 “{{ nowSelectRole.name }}” 的菜单绑定
            </a-button>
          </a-popconfirm>
        </template>
        <a-table :columns="columns" :data-source="roleMenuTree" :row-selection="rowSelection" selectedRowKeys>
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'operationLevel'">
              <a-select @change="menuLevelChange(record)" :disabled="record.children!=null"
                        v-model:value="record.operationLevel" :options="menuLevelOption"></a-select>
            </template>
          </template>
        </a-table>
      </container>
    </div>
    <div v-else class="page-notInfo">
      <div class="img-box">
        <img src="@/assets/emptyImg/empty.png" alt="">
      </div>
      <span>暂无角色信息</span>
    </div>

    <a-modal :open="modalConfig.modalVisible" :title="modalConfig.modalTitle" centered :closable="false"
             :maskClosable="false">
      <a-form :model="modalFormData">
        <a-form-item label="角色名称：">
          <a-input size="large" v-model:value="modalFormData.name" placeholder="请输入"/>
        </a-form-item>
      </a-form>
      <template #footer>
        <a-button key="back" @click="modalCancelClick">取消</a-button>
        <a-button key="submit" type="primary" @click="modalOperationClick">
          {{ modalConfig.modalTitle.substring(0, 2) }}
        </a-button>
      </template>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import maskLayer from "@/components/MaskLayer/index.vue"
import {computed, createVNode, onMounted, ref, watch} from "vue";
import {message, Modal} from "ant-design-vue";
import {ExclamationCircleOutlined} from "@ant-design/icons-vue";
import Container from "@/components/Container/Container.vue";
import {
  addRoleRequest, deleteRoleRequest, getAllRole,
  getRoleMenuRel, updateRoleMenuRel, updateRoleRequest
} from "@/api/basicsApi/systemManage/RoleManage.ts";
import {getMenuTree} from "@/api/basicsApi/systemManage/MenuManage.ts";
import {columns, menuLevelOption} from "./Model.ts";
import {getLoginInfo, systemLogout} from "@/utils/auth.ts";
import {LoginInfo, MenuOperationInfo, RoleInfo, RoleMenuTreeNode} from "@/interface/basicsInterface/systemManage";

const nowSelectRole = ref<RoleInfo | null>(null) // 当前选中的角色信息
const roleMenuTree = ref<RoleMenuTreeNode[]>([]) // 树节点数据
let newRoleMenuRelList = ref<MenuOperationInfo[]>([])  // 拿到选中的树节点的id和操作权限
const isLoading = ref(false)
const allMenuTreeDataList = ref<any>([]) // 所有的菜单树数据
const allRoleDataList = ref<any>([]) // 所有角色
const modalConfig = ref({
  modalVisible: false,
  modalTitle: ""
})
const modalFormData = ref({
  name: null,
  menuLevel: null,
  menuId: undefined,
  roleId: null
})
const popConfirmIsOpen = ref<boolean>(false); // 判断当前修改角色是否绑定在当前登录用户上
const loginInfo: LoginInfo = JSON.parse(getLoginInfo())

const rowSelection = computed(() => {
  return {
    selectedRowKeys: newRoleMenuRelList.value.map((res: MenuOperationInfo) => res.menuId),
    onChange: (_: (string | number)[], selectedRows: RoleMenuTreeNode[]) => {
      newRoleMenuRelList.value = selectedRows.map((res: RoleMenuTreeNode) => {
        return {
          menuId: res.key,
          menuLevel: res.operationLevel
        }
      })
    }
  }
})

watch(nowSelectRole, (newValue: RoleInfo | null) => {
  if (!newValue) return
  getRoleMenuRel(newValue.roleId).then(res => {
    if (!res.data) return
    const menuOperationList = res.data as MenuOperationInfo[]
    roleMenuTree.value = parseMenuTreeToRoleMenuTree(allMenuTreeDataList.value, menuOperationList)
    newRoleMenuRelList.value = menuOperationList
  })
})

onMounted(async () => {
  await getAllRoleFun()
  const {data} = await getMenuTree()
  allMenuTreeDataList.value = data.children
})

// 更改已经选中的树节点的操作权限
function menuLevelChange(roleMenuTreeNode: RoleMenuTreeNode) {
  const changeRel = newRoleMenuRelList.value.find((item: MenuOperationInfo) => item.menuId == roleMenuTreeNode.key)
  if (changeRel) {
    changeRel.menuLevel = roleMenuTreeNode.operationLevel
  }
}

// 右上角菜单绑定更新按钮
function updateRoleMenuClick() {
  if (loginInfo.roles[0].roleId == nowSelectRole.value?.roleId) {
    popConfirmIsOpen.value = true
  } else {
    updateRoleMenu(false)
  }
}

// 更新角色的可操作菜单
function updateRoleMenu(needExitSystem: Boolean) {
  isLoading.value = true
  updateRoleMenuRel(nowSelectRole.value?.roleId, newRoleMenuRelList.value).then((res: any) => {
    message.success(res.msg)
    isLoading.value = false
    if (needExitSystem) {
      systemLogout()
    }
  }).catch(() => {
    isLoading.value = false
  })
}

function parseMenuTreeToRoleMenuTree(menuTree: any[], roleMenuBindingList: MenuOperationInfo[]): RoleMenuTreeNode[] {
  const tree: RoleMenuTreeNode[] = []
  for (const menu of menuTree) {
    const roleMenuBindingInfo = roleMenuBindingList.find((item: MenuOperationInfo) => item.menuId === menu.menuId) ?? {
      menuId: menu.menuId as number,
      menuLevel: "ROOT"
    }
    tree.push({
      key: menu.menuId,
      name: menu.name,
      operationLevel: roleMenuBindingInfo.menuLevel,
      children: menu.children.length != 0 ? parseMenuTreeToRoleMenuTree(menu.children, roleMenuBindingList) : undefined
    })
  }
  return tree
}

// 获取所有角色
async function getAllRoleFun() {
  isLoading.value = true
  await getAllRole().then((res: any) => {
    allRoleDataList.value = res.data
  })
  isLoading.value = false
}

// 可操作菜单查看按钮
function viewDetailsClick(record: any) {
  nowSelectRole.value = {
    boundUserCount: record.boundUserCount,
    name: record.roleName,
    roleId: record.roleId
  }
}

// 新增角色按钮
function addRoleClick() {
  modalConfig.value.modalVisible = true
  modalFormData.value.name = null
  modalConfig.value.modalTitle = '新增角色：'
}

function editRoleClick(record: any) {
  modalFormData.value.name = record.roleName
  modalFormData.value.roleId = record.roleId
  modalConfig.value.modalTitle = '更新角色信息：'
  modalConfig.value.modalVisible = true
}

// 删除角色按钮
function deleteRoleClick(record: any) {
  Modal.confirm({
    title: "您确定删除此项吗？",
    icon: createVNode(ExclamationCircleOutlined),
    centered: true,
    onOk() {
      deleteRoleRequest(record.roleId).then((res: any) => {
        message.success(res.msg)
        getAllRoleFun()
      })
    },
    onCancel() {
      message.info('已取消删除操作');
    },
    class: 'test',
  });
}

// 弹窗取消按钮
function modalCancelClick() {
  modalConfig.value.modalVisible = false
  modalFormData.value.name = null
  modalFormData.value.roleId = null
}

// 弹窗操作按钮（注册/更新）角色
function modalOperationClick() {
  isLoading.value = true
  if (modalConfig.value.modalTitle.substring(0, 2) === '新增') {
    addRoleRequest(modalFormData.value.name,).then((res: any) => {
      message.success(res.msg)
      getAllRoleFun()
      modalConfig.value.modalVisible = false
      isLoading.value = false
    }).catch(() => {
      modalConfig.value.modalVisible = false
      isLoading.value = false
    })
  } else {
    updateRoleRequest(modalFormData.value.roleId, modalFormData.value.name).then((res: any) => {
      message.success(res.msg)
      isLoading.value = false
      modalConfig.value.modalVisible = false
      getAllRoleFun()
    }).catch(() => {
      isLoading.value = false
      modalConfig.value.modalVisible = false
    })
  }
}
</script>

<style scoped lang="scss">
@use "@/styles/PublicTable.scss";
@use "@/styles/TreeCss";

.role-container {
  position: relative;
  height: 100%;
  width: 100%;
  padding: 0 20px 20px 20px;
  color: white;

  .top-container {
    width: 100%;
    height: 8%;
    display: flex;
    align-items: center;
  }

  .bot-container {
    width: 100%;
    height: 92%;
    display: flex;
    justify-content: space-between;

    .table-container {
      width: 59%;
      height: 100%;
    }
  }
}

:deep(.ant-tree) {
  background-color: rgba(255, 255, 255, 0);
}

:deep(.ant-tree .ant-tree-treenode) {
  display: flex;
}
</style>
